#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
批量测试AES加密评论详情查询
测试多个确认存在的评论ID
"""

import json
import base64
import time
import requests
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto.Random import get_random_bytes

def aes_encrypt(data_dict, secret_key="qwertyuiop1234567654zaqwsxcderfv"):
    """AES加密函数（与Flutter完全一致）"""
    # 处理密钥
    key_bytes = secret_key.encode('utf-8')[:32].ljust(32, b'\0')
    
    # 添加timestamp
    data_dict['timestamp'] = int(time.time())
    
    # 转换为JSON
    json_data = json.dumps(data_dict, separators=(',', ':'))
    
    # 生成随机IV
    iv = get_random_bytes(16)
    
    # AES加密
    cipher = AES.new(key_bytes, AES.MODE_CBC, iv)
    padded_data = pad(json_data.encode('utf-8'), AES.block_size)
    encrypted = cipher.encrypt(padded_data)
    
    # 组合并Base64编码
    combined = iv + encrypted
    encrypted_b64 = base64.b64encode(combined).decode('utf-8')
    
    return {
        "encrypted_data": encrypted_b64,
        "original_data": json_data
    }

def test_comment_detail(comment_id, test_name):
    """测试单个评论详情"""
    print(f"\n🧪 =============== 测试 {test_name} (ID: {comment_id}) ===============")
    
    try:
        # 准备数据
        original_data = {"commentId": comment_id}
        
        # AES加密
        encrypted_result = aes_encrypt(original_data.copy())
        encrypted_payload = {"encrypted_data": encrypted_result["encrypted_data"]}
        
        print(f"📊 原始数据: {encrypted_result['original_data']}")
        print(f"🔒 加密载荷: {json.dumps(encrypted_payload)}")
        
        # 发送AES请求
        print(f"\n🔐 发送AES加密请求...")
        aes_response = requests.post(
            "http://124.71.77.44:2233/comments/detail/",
            json=encrypted_payload,
            headers={"Content-Type": "application/json"},
            timeout=10
        )
        
        print(f"📨 AES状态码: {aes_response.status_code}")
        try:
            aes_json = aes_response.json()
            print(f"📨 AES响应: {json.dumps(aes_json, ensure_ascii=False)}")
        except:
            print(f"📨 AES响应文本: {aes_response.text}")
        
        # 发送明文请求对比
        print(f"\n📝 发送明文请求对比...")
        plaintext_data = {"commentId": comment_id, "timestamp": int(time.time())}
        
        plaintext_response = requests.post(
            "http://124.71.77.44:2233/comments/detail/",
            json=plaintext_data,
            headers={"Content-Type": "application/json"},
            timeout=10
        )
        
        print(f"📨 明文状态码: {plaintext_response.status_code}")
        try:
            plaintext_json = plaintext_response.json()
            print(f"📨 明文响应: {json.dumps(plaintext_json, ensure_ascii=False)}")
        except:
            print(f"📨 明文响应文本: {plaintext_response.text}")
        
        # 生成curl命令
        print(f"\n📋 生成的curl命令:")
        print(f"# AES加密:")
        print(f'''curl -X POST "http://124.71.77.44:2233/comments/detail/" \\
  -H "Content-Type: application/json" \\
  -d '{json.dumps(encrypted_payload)}' ''')
        
        print(f"\n# 明文:")
        print(f'''curl -X POST "http://124.71.77.44:2233/comments/detail/" \\
  -H "Content-Type: application/json" \\
  -d '{json.dumps(plaintext_data)}' ''')
        
        return {
            "comment_id": comment_id,
            "aes_success": aes_response.status_code == 200,
            "plaintext_success": plaintext_response.status_code == 200,
            "aes_response": aes_response.text,
            "plaintext_response": plaintext_response.text
        }
        
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        return None

def main():
    """主测试函数"""
    print("🔐 =============== 批量AES加密测试 ===============")
    
    # 测试用例 - 从用户日志中确认存在的评论ID
    test_cases = [
        {"id": 53, "name": "健身房评论"},
        {"id": 49, "name": "测试评论(可能已删除)"},
        {"id": 1, "name": "ID为1的评论"},
    ]
    
    results = []
    
    for case in test_cases:
        result = test_comment_detail(case["id"], case["name"])
        if result:
            results.append(result)
        time.sleep(1)  # 避免请求过快
    
    # 总结
    print(f"\n📊 =============== 测试总结 ===============")
    for result in results:
        comment_id = result["comment_id"]
        aes_status = "✅ 成功" if result["aes_success"] else "❌ 失败"
        plaintext_status = "✅ 成功" if result["plaintext_success"] else "❌ 失败"
        
        print(f"评论ID {comment_id}:")
        print(f"  - AES加密: {aes_status}")
        print(f"  - 明文方式: {plaintext_status}")
        
        # 检查响应内容
        if '"status":"success"' in result["aes_response"]:
            print(f"  - 🎉 AES解密成功！")
        elif '"缺少评论ID"' in result["aes_response"]:
            print(f"  - ⚠️ AES解密失败：缺少评论ID")
        
        if '"status":"success"' in result["plaintext_response"]:
            print(f"  - ✅ 明文请求成功")
        elif '"缺少评论ID"' in result["plaintext_response"]:
            print(f"  - ❌ 明文请求失败：缺少评论ID")
        
        print()
    
    print("🏁 =============== 测试完成 ===============")

if __name__ == "__main__":
    main()
